<template>
  <div class="Nationalorders">
    <div class="filter_container">
      <el-form :inline="true" :model="nationalForm" class="demo-form-inline">
        <el-form-item label="城市">
          <el-select v-model="deptIdsIdslist" size="small" placeholder="请选择城市" multiple @change="getdeptIdsIds"
            ref='deptNameRef' @keydown.native="selectBlur($event)" clearable collapse-tags>
            <el-option v-for="item in cityList" :key="item.id" size="small" :label="item.deptName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类别" style="margin-bottom: 15px!important;">
            <el-select 
                ref="channelTypeRef" 
                v-model="channelType" 
                @keydown.native="selectBlur($event)" 
                clearable 
                filterable 
                size="medium" 
                placeholder="渠道类别" 
                style="width: 155px"
                @change="channel = ''"
            >    
            <el-option v-for="(channelItem,channel) in channelTypeList" :key="channel" :label="channelItem.channelName"
              :value="channelItem.channelKey">
              <span :data-id="channelItem.id" style="display: inline-block;width: 150px;padding: 0 20px;margin-left: -20px;"
                @click="getChannelTypeId($event)">{{ channelItem.channelName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" style="margin-bottom: 15px!important;">
          <el-select ref="channelRef" v-model="channel" @keydown.native="selectBlur($event)" size="medium" clearable filterable placeholder="渠道" style="width: 155px">
            <el-option v-for="(channelItem,channel) in channelList" :key="channel" :label="channelItem.channelName"
              :value="channelItem.channelKey"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="时间类型">

        </el-form-item> -->
        <el-form-item label="选择日期">
          <el-select v-model="nationalForm.timeType" size="small" clearable style='width:100px;margin-right:10px;' ref='timeTypeRef' @keydown.native="selectBlur($event)">
            <el-option v-for="item in TimesList" :key="item.value" :label="item.value" :value="item.label">
            </el-option>
          </el-select>
          <el-date-picker size="small" v-model="Launchdate" type="daterange" range-separator="至" start-placeholder="开始日期"
            :clearable='false' end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain size="small" icon="el-icon-search" @click="handleFilterNational(nationalForm,Launchdate)">查询</el-button>
          <el-button type="success" plain size="small" v-xmbz-permission="'statistics_order_order_export'" icon="el-icon-download" @click="handleExportNational(nationalForm,Launchdate)"  onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}">导出</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="Nationalorders-list">
      <el-table :data="NationalordersList" border style="width: 100%">
        <!-- <el-table-column label="全国订单数据" align='center'> -->
        <el-table-column label="后台单号" width="180" prop="xmbzNo" fixed :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="订单状态" width="100" prop="status" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="配送地址" width="300" prop="receiverAddress" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="配送日期" width="120" prop="deliveryDate" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="配送时间" width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope"> {{scope.row.deliveryStartTime}}~{{scope.row.deliveryEndTime}}</template>
        </el-table-column>
        <el-table-column label="商品档案编码" width="240" prop="skuId" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="蛋糕名称" width="300" prop="goodsName" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="规格" width="200" prop="goodsSpecs" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="数量" width="120" prop="num" :show-overflow-tooltip="true">
        </el-table-column>
           <el-table-column label="商品类型" width="120" prop="categoryName" :show-overflow-tooltip="true">
        </el-table-column>
        <!-- <el-table-column label="下单员" width="120" prop="orderer">
        </el-table-column> -->
        <el-table-column label="配送员" width="120" prop="delivery" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="财务需求" width="200" prop='merchantName' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="配送需求" width="120" porp='deliveryRemark' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="生产需求" width="120" prop='generateRemark' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="团购码" width="200" prop='platformOrderId' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="渠道" width="200" prop='channelName' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="祝福语" width="300" prop='blessings' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="客户备注" width="380" prop='consumerRemark' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="客服备注" width="380" prop='customerServiceNotes' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="异常反馈" width="380" prop='abnormalContent' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="总仓" width="80" prop="mainWarehouse" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="分仓" width="80" prop='branchWarehouse' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="签收时间" width="180" prop='receivedTime' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="下单时间" width="180" prop='orderTime' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="操作人" width="120" prop='operator' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="城市" width="120" prop='deptName' fixed='right' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="订单总价" width="120" prop='originalPrice' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="商品价格" width="120" prop='productPrice' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="付款金额" width="120" prop='totalPrice' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="配送费" width="120" prop='postPrice' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="优惠金额" width="120" prop='discountPrice' :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="是否跳舞" width="120" prop="isDance">
          <template slot-scope="{row}">
            <span>{{ danceLabelMap[row.isDance] || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>

    </div>
  </div>
</template>

<script>
  import { deptdepts } from "@/api/shop"
  import { danceLabelMap } from '@/const'
  import { getExcelShowData } from "@/api/statistics"
  // 渠道  // 渠道类别列表 
  import { getOrderChannelList, getOrderChannelTypeList, } from '@/api/createOrder';
  
  export default {
    data() {
      return {
        nationalForm: {
          excelType: 'ORDER', //订单统计
          deptIds: [],
          startTime: this.dayjs(new Date()).format("YYYY-MM-DD"),
          endTime: this.dayjs(new Date()).format("YYYY-MM-DD"),
          timeType: 2,
        },
        cityList: [], //城市
        TimesList: [{
          value: '下单时间',
          label: 1
        }, {
          value: '配送时间',
          label: 2
        }],
        NationalordersList: [ //全国订单数据],
        ],
        deptIdsIdslist: [],
        Launchdate: [
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD")
          .toString(),
          this.dayjs(
            new Date()
          )
          .format("YYYY-MM-DD")
          .toString(),
        ],
        danceLabelMap,
        channelType: '',
        channel:'', 
        channelTypeList: '', // 渠道类别列表
        channelList: '', //渠道
        getChannelList: { // 渠道列表
          parentId: ''
        },
      }
    },
    mounted() {
      this.citydataList().then(() => {
        if (this.cityList && this.cityList.length) {
          this.deptIdsIdslist = [this.cityList[0].id]
        }
        this.getOrderList();
      });
      window.addEventListener("keydown", this.keyupEnter);
        // 渠道类别表列
        getOrderChannelTypeList().then(res => {
            this.channelTypeList = res.data.data;
        })
    },
    methods: {
        // 渠道类别发生改变
        channelTypeChange(e) {
            
        },
        // 选择渠道类型
      getChannelTypeId(e) {
        // 渠道列表接口
        this.getChannelList.parentId = e.currentTarget.dataset.id
        // 渠道列表接口
        getOrderChannelList(this.getChannelList).then(res => {
          let result = res.data.data;
          result.forEach(item => {
            this.channelList = result;
            if (this.nationalForm.channel !== undefined) {
              if (item.channelKey == this.nationalForm.channel) {
                this.channelList = result
              } else {
                this.channelList = result;
                this.nationalForm.channel = ''
              }
            }
          })
        })
      },
      // 选择框回车失焦
      selectBlur(e) {
        if (e.keyCode == 13) {
          this.$refs.deptNameRef.blur();
          this.$refs.timeTypeRef.blur();
          e.returnValue = false;
        }
      },
      // 回车事件
      keyupEnter() {
        if (window.event.keyCode == 13) {
          this.handleFilterNational(this.nationalForm, this.Launchdate); // 查询事件
        }
      },
      //如果页面有keep-alive缓存功能，这个函数会触发
      activated() {
        window.addEventListener("keydown", this.keyupEnter);
      },
      deactivated() {
        window.removeEventListener("keydown", this.keyupEnter);
      },

      citydataList() {
        return deptdepts("").then(response => {
          this.cityList = response.data.data
          if (this.cityList) {
            this.cityList.unshift({
              deptName: '全选',
              id: 'all'
            })
          }
        });
      },
      getdeptIdsIds(data) {
        if (!data || !data.length) {
          this.$message({
            type: 'warning',
            message: '城市不能为空！'
          })
          this.deptIdsIdslist = [this.cityList[0].id]
        }
      },
      // headlegettimeType(item) {
      //   this.gettimeType = item;
      // },
      getOrderList() {
        // 订单列表分页
        const params = this.getParams()
        getExcelShowData(params).then(response => {
          this.NationalordersList = response.data.data;
        });
      },
      getParams() {
        return {
          excelType: this.nationalForm.excelType, //订单统计
          deptIds: this.deptIdsIdslist.includes('all') ? this.cityList.map(item => item.id).filter(item => item != 'all').join(',') : this.deptIdsIdslist.join(','),
          startTime: this.nationalForm.startTime,
          endTime: this.nationalForm.endTime,
          channelIds: this.channel || undefined,
          timeType: this.nationalForm.timeType,
        }
      },
      handleFilterNational(nationalForm, times) { //查询
        if(this.channelType) {
            if(!this.channel) {
                this.$message({
                    message: '请先选择渠道!',
                    type: 'warning'
                })
                return
            }
        }
        // if (this.nationalForm.startTime) {
        //   this.nationalForm.startTime = this.dayjs(
        //       this.nationalForm.startTime
        //     )
        //     .format("YYYY-MM-DD")
        //     .toString();
        // } else {
        //   this.nationalForm.startTime = ''
        // }
        // if (this.nationalForm.endTime) {
        //   this.nationalForm.endTime = this.dayjs(
        //       this.nationalForm.endTime
        //     )
        //     .format("YYYY-MM-DD")
        //     .toString();
        // } else {
        //   this.nationalForm.endTime = ''
        // }
        nationalForm.deptIds = this.deptIdsIdslist.join(',');
        // nationalForm.timeType = this.gettimeType
        if (times) {
          this.nationalForm.startTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD")
            .toString();
          this.nationalForm.endTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD")
            .toString();
        }
        var time1 = Date.parse(this.nationalForm.startTime);
        var time2 = Date.parse(this.nationalForm.endTime);
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 30) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          this.getOrderList();
        }

      },
      handleExportNational(nationalForm, times) { //导出
        let {
          startTime = "", endTime = "", deptIds = '',
        } = this.nationalForm
        // startTime = this.dayjs(startTime)
        //   .format("YYYY-MM-DD")
        //   .toString();
        // endTime = this.dayjs(endTime)
        //   .format("YYYY-MM-DD")
        //   .toString();
        // var time1 = Date.parse(startTime);
        // var time2 = Date.parse(endTime);
        //讲两个时间相减，求出相隔的天数
        // var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        nationalForm.deptIds = this.deptIdsIdslist.join(',');
        if (times) {
          this.nationalForm.startTime = this.dayjs(
              times[0]
            )
            .format("YYYY-MM-DD")
            .toString();
          this.nationalForm.endTime = this.dayjs(
              times[1]
            )
            .format("YYYY-MM-DD")
            .toString();
        }
        var time1 = Date.parse(this.nationalForm.startTime);
        var time2 = Date.parse(this.nationalForm.endTime);
        //讲两个时间相减，求出相隔的天数
        var dayCount = Math.abs(time2 - time1) / 1000 / 60 / 60 / 24;
        if (dayCount > 30) {
          this.$message({
            showClose: true,
            message: "时间间隔不可超过31天",
            type: "warning"
          });
        } else {
          // const {
          //   user
          // } = this.$store.state
          var user = JSON.parse(localStorage.getItem('saber-userInfo'));
          const params = this.getParams()
          window.open(
            `/api/xmbz-statistics/orderStatistics/downLoadOrderExcel?excelType=ORDER&startTime=${params.startTime}&endTime=${params.endTime}&deptIds=${params.deptIds}&timeType=${params.timeType}&blade-auth=bearer ${user['content'].accessToken}`
          );
          console.log(
            `/api/xmbz-statistics/orderStatistics/downLoadOrderExcel?excelType=ORDER&startTime=${params.startTime}&endTime=${params.endTime}&deptIds=${params.deptIds}&timeType=${params.timeType}&blade-auth=bearer ${user['content'].accessToken}`
          )
        }
      }
    }

  }
</script>

<style lang='scss' scoped>
  .Nationalorders {
    padding-top: 20px;
    border-top: 1px solid #ccc;

    .filter_container {
      display: flex;

      .el-form-item {
        margin-bottom: 22px !important;
      }
    }
  }
</style>
